//
//  UIView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/20/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.


import UIKit

extension UIView {
    
    func addBorder (width: CGFloat, color: UIColor, height: CGFloat?=2, isTop: Bool?=false) {
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.frame = CGRect(x: (self.frame.width - width) / 2,
                              y: isTop! ? 0 : self.frame.size.height - height!,
                              width: width,
                              height: height!)
        self.layer.addSublayer(border)
    }
    
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
    
    func addLeftBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
        let border = UIView()
        border.backgroundColor = color
        border.frame = CGRect(x: 0, y: 0, width: borderWidth, height: frame.size.height)
        border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
        addSubview(border)
    }

    func addRightBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
        let border = UIView()
        border.backgroundColor = color
        border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
        border.frame = CGRect(x: frame.size.width - borderWidth, y: 0, width: borderWidth, height: frame.size.height)
        addSubview(border)
    }
    
    func addTopBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
        let border = UIView()
        border.backgroundColor = color
        border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
        border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderWidth)
        addSubview(border)
    }

    func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
        let border = UIView()
        border.backgroundColor = color
        border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
        border.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
        addSubview(border)
    }
}

extension UISegmentedControl {
    
    func roundCorners () {
        for (index, subview) in subviews.enumerated() {
            if ((subviews[index] as? UIImageView) != nil) && index == selectedSegmentIndex {
                subview.backgroundColor = .white
                subview.layer.cornerRadius = subview.frame.height / 2
            } else {
                subview.backgroundColor = .clear
            }
        }
    }
}


extension UIScrollView {
    var currentPage: Int {
        return Int((contentOffset.x + (0.5 * frame.size.width)) / frame.width)
    }
}
